package com.library.librarybackend.handler.async;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;

import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * @author 平
 * @description 异步任务执行类
 * @date 2025-02-20 12:07:14
 */
@Slf4j
public class AsyncTaskExecute {

    @Async
    public <T, R> CompletableFuture<R> execute(Function<T, R> task, T arg) {
        R obj = null;
        try {
            obj = task.apply(arg);
        } catch (Exception e) {
            log.error("异步异常 ->", e);
        }
        return CompletableFuture.completedFuture(obj);
    }

    @Async
    public <T> void execute(Consumer<T> task, T arg) {
        try {
            task.accept(arg);
        } catch (Exception e) {
            log.error("异步异常 ->", e);
        }
    }

    @Async
    public <R> CompletableFuture<R> execute(Supplier<R> task) {
        R obj = null;
        try {
            obj = task.get();
        } catch (Exception e) {
            log.error("异步异常 ->", e);
        }
        return CompletableFuture.completedFuture(obj);
    }

    @Async
    public void execute(Runnable task) {
        try {
            task.run();
        } catch (Exception e) {
            log.error("异步异常 ->", e);
        }
    }


}
